<?php
namespace app\controller;

use app\service\MqttClient;
use think\Controller;
use think\facade\Config;

class Api extends Controller
{

    public function test()
    {
        echo 1;exit;

    }
    /**
     * 发布MQTT消息的API接口
     * 
     * @return \think\response\Json
     */
    public function publishMqtt()
    {
        // 获取参数
        $topic = $this->request->param('topic');
        $message = $this->request->param('message');
        $qos = (int)$this->request->param('qos', 0);
        $apiKey = $this->request->param('api_key');
        
        // 验证API密钥 (实际应用中应该使用更安全的认证方式)
        $validApiKey = Config::get('api.key', '123456');
        if ($apiKey !== $validApiKey) {
            return json(['code' => 401, 'msg' => '未授权的访问']);
        }
        
        // 验证必填参数
        if (empty($topic)) {
            return json(['code' => 400, 'msg' => '主题不能为空']);
        }
        
        if (empty($message)) {
            return json(['code' => 400, 'msg' => '消息内容不能为空']);
        }
        
        // 验证QoS
        if ($qos < 0 || $qos > 2) {
            return json(['code' => 400, 'msg' => 'QoS值必须为0-2']);
        }
        
        // 获取MQTT配置
        $config = Config::get('mqtt.');
        
        try {
            // 创建MQTT客户端
            $mqtt = new MqttClient($config);
            
            // 连接到MQTT服务器
            if (!$mqtt->connect()) {
                return json(['code' => 500, 'msg' => '连接MQTT服务器失败']);
            }
            
            // 发布消息
            $result = $mqtt->publish($topic, $message, $qos);
            
            // 断开连接
            $mqtt->disconnect();
            
            if ($result) {
                return json([
                    'code' => 200, 
                    'msg' => '消息发布成功', 
                    'data' => [
                        'topic' => $topic,
                        'qos' => $qos,
                        'time' => date('Y-m-d H:i:s')
                    ]
                ]);
            } else {
                return json(['code' => 500, 'msg' => '消息发布失败']);
            }
            
        } catch (\Throwable $e) {
            return json(['code' => 500, 'msg' => '发生错误: ' . $e->getMessage()]);
        }
    }
} 